package com.qfedu.service.impl;

import com.qfedu.entity.AdminEntity;
import com.qfedu.mapper.AdminPojoMapper;
import com.qfedu.pojo.AdminPojo;
import com.qfedu.service.AdminService;
import org.apache.ibatis.annotations.Param;
import org.apache.tools.ant.taskdefs.Echo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class AdminServiceimpl implements AdminService {
    @Autowired
    AdminPojoMapper adminPojoMapper;

    @Override
    public AdminPojo dologin(AdminEntity adminEntity) {
        if (adminEntity.getApass()!=null && !"".equals(adminEntity.getApass())){
            String pass = DigestUtils.md5DigestAsHex(adminEntity.getApass().getBytes());
            System.out.println(pass);
            adminEntity.setApass(pass);
        }

        AdminPojo adminPojo = adminPojoMapper.dologin(adminEntity);
        return adminPojo;
    }

    @Override
    public List<AdminPojo> queryAlladmin(AdminEntity adminEntity) {
        List<AdminPojo> list = adminPojoMapper.queryAlladmin(adminEntity);
        return list;
    }

    @Override
    public Boolean deleteAdById( String aidstr) {
        aidstr="("+aidstr.substring(0,aidstr.length()-1)+")";
        Boolean flag = adminPojoMapper.deleteAdById(aidstr);
        return flag;
    }

    @Override
    public Boolean addAdmin(AdminEntity adminEntity) {
        Boolean flag = adminPojoMapper.addAdmin(adminEntity);
        System.out.println(adminEntity.getAid());
        String[] roles = adminEntity.getRoles();
        for (int i = 0; i < roles.length; i++) {
                Boolean bool = adminPojoMapper.addAdminWithRole(adminEntity.getAid(), Integer.parseInt(roles[i]));
             if (!bool){
                 try {
                     throw new Exception("添加用户错误");
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
             }
        }
        return true;
    }

    @Override
    public Boolean untying(AdminEntity adminEntity) {
        Boolean flag = adminPojoMapper.untying(adminEntity.getAid());
        Boolean flag03 = adminPojoMapper.updateAdmin(adminEntity);
        if (!flag03){
            return false;
        }
        String[] roles = adminEntity.getRoles();
        for (String rid:roles){
            Boolean flag01 = adminPojoMapper.addAdminWithRole(adminEntity.getAid(), Integer.parseInt(rid));
            if (!flag01){
               return false;
            }
        }
        return true;
    }

    @Override
    public Boolean updateAdminStatus(AdminEntity adminEntity) {
        Boolean flag = adminPojoMapper.updateAdmin(adminEntity);

        return flag;
    }
}
